# app/routes/courses.py

from flask import Blueprint, render_template, request, redirect, url_for, flash
from app.models.models import Courses
from app import db

courses = Blueprint('courses', __name__)

@courses.route('/courses')
def list_courses():
    courses = Courses.query.all()
    return render_template('courses/list.html', courses=courses)

@courses.route('/course/add', methods=['GET', 'POST'])
def add_course():
    if request.method == 'POST':
        name = request.form.get('name')
        description = request.form.get('description')
        new_course = Courses(name=name, description=description)
        db.session.add(new_course)
        db.session.commit()
        flash('Course added successfully')
        return redirect(url_for('courses.list_courses'))
    return render_template('courses/add.html')

@courses.route('/course/edit/<int:id>', methods=['GET', 'POST'])
def edit_course(id):
    course = Courses.query.get_or_404(id)
    if request.method == 'POST':
        course.name = request.form.get('name')
        course.description = request.form.get('description')
        db.session.commit()
        flash('Course updated successfully')
        return redirect(url_for('courses.list_courses'))
    return render_template('courses/edit.html', course=course)

@courses.route('/course/delete/<int:id>', methods=['POST'])
def delete_course(id):
    course = Courses.query.get_or_404(id)
    db.session.delete(course)
    db.session.commit()
    flash('Course deleted successfully')
    return redirect(url_for('courses.list_courses'))
